package com.jcsz.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jcsz.common.utils.R;
import com.jcsz.gulimall.product.entity.*;
import com.jcsz.gulimall.product.feign.SeckillFeignService;
import com.jcsz.gulimall.product.service.*;
import com.jcsz.gulimall.product.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcsz.common.utils.PageUtils;
import com.jcsz.common.utils.Query;

import com.jcsz.gulimall.product.dao.SkuInfoDao;
import org.springframework.util.StringUtils;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private SeckillFeignService seckillFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * {
     * page: 1,//当前页码
     * limit: 10,//每页记录数
     * sidx: 'id',//排序字段
     * order: 'asc/desc',//排序方式
     * key: '华为',//检索关键字
     * catelogId: 0,
     * brandId: 0,
     * min: 0,
     * max: 0
     * }
     **/
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(obj -> {
                obj.eq("sku_id", key).or().like("sku_name", key);
            });
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {

            queryWrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }

        String minValue = (String) params.get("min");
        if (!StringUtils.isEmpty(minValue)) {
            BigDecimal min = new BigDecimal(minValue);
            queryWrapper.ge("price", min);
        }

        String msxValue = (String) params.get("max");
        if (!StringUtils.isEmpty(msxValue)) {
            try {
                BigDecimal max = new BigDecimal(msxValue);
                if (max.compareTo(new BigDecimal("0")) == 1) {
                    queryWrapper.le("price", max);
                }
            } catch (Exception exception) {

            }

        }

        IPage<SkuInfoEntity> page = this.page(new Query<SkuInfoEntity>().getPage(params), queryWrapper);

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> spus = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return spus;
    }

    public SkuItemVo3 getSkuDeatilBySkuId3(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo3 skuItemVo3 = new SkuItemVo3();

        //sku基本信息    SkuInfoEntity skuInfo;
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity skuInfo = getById(skuId);
            skuItemVo3.setInfo(skuInfo);
            return skuInfo;
        }, executor);
        //sku图片信息    List<SkuImagesEntity> images;
        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> images = skuImagesService.getSkuImagesBySkuId(skuId);
            skuItemVo3.setImages(images);
        }, executor);

        //spu描述       SpuInfoDescEntity spuInfoDesc;
        CompletableFuture<Void> spuInfoDescFuture = infoFuture.thenAcceptAsync((skuInfo) -> {
            SpuInfoDescEntity spuInfoDesc = spuInfoDescService.getById(skuInfo.getSpuId());
            skuItemVo3.setDesc(spuInfoDesc);
        }, executor);
        //sku销售属性   List<SkuItemSaleAttrVo> saleAttr
        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync((skuInfo) -> {
            List<SkuItemSaleAttrVo2> saleAttr = skuSaleAttrValueService.getSaleAttrBySpuId2(skuInfo.getSpuId());
            skuItemVo3.setSaleAttr(saleAttr);
        }, executor);
        //spu规格参数    List<SkuItemAttrGroupVo> groupAttrs;
        CompletableFuture<Void> groupAttrFuture = infoFuture.thenAcceptAsync((skuInfo) -> {
            List<SpuItemAttrGroupVo> groupAttrs = attrGroupService.getAttrGroupWithAttrBySpuId(skuInfo.getSpuId(), skuInfo.getCatalogId());
            skuItemVo3.setGroupAttrs(groupAttrs);
        }, executor);
        //sku秒杀信息
        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            R r = seckillFeignService.getSkuSeckilInfo(skuId);
            if (r.getCode() == 200) {
                SeckillSkuVo data = r.getData(new TypeReference<SeckillSkuVo>() {
                });
                if (data != null) {
                    long currentTime = System.currentTimeMillis();
                    if (currentTime > data.getEndTime()) {
                        skuItemVo3.setSeckillSkuVo(null);
                    }
                }
                skuItemVo3.setSeckillSkuVo(data);
            }
        }, executor);
        CompletableFuture.allOf(imagesFuture, spuInfoDescFuture, saleAttrFuture, groupAttrFuture, seckillFuture).get();
        System.out.println(JSON.toJSON(skuItemVo3));
        return skuItemVo3;
    }

    public SkuItemVo2 getSkuDeatilBySkuId2(Long skuId) {
        SkuItemVo2 skuItemVo2 = new SkuItemVo2();
        //sku基本信息    SkuInfoEntity skuInfo;
        SkuInfoEntity skuInfo = getById(skuId);
        skuItemVo2.setSkuInfo(skuInfo);
        //sku图片信息    List<SkuImagesEntity> images;
        List<SkuImagesEntity> images = skuImagesService.getSkuImagesBySkuId(skuId);
        skuItemVo2.setImages(images);
        Long spuId = skuInfo.getSpuId();
        //sku销售属性   List<SkuItemSaleAttrVo> saleAttr
        List<SkuSaleAttrValueEntity> saleAttrs = skuSaleAttrValueService.list(new QueryWrapper<SkuSaleAttrValueEntity>().eq("sku_id", skuId));
        List<SkuItemVo2.SkuItemSaleAttrVo> collect = saleAttrs.stream().map(attr -> {
            SkuItemVo2.SkuItemSaleAttrVo skuItemSaleAttrVo = new SkuItemVo2.SkuItemSaleAttrVo();
            skuItemSaleAttrVo.setAttrId(attr.getAttrId());
            skuItemSaleAttrVo.setAttrName(attr.getAttrName());
            List<Long> skuIds = baseMapper.getSkuIdsBySpuId(spuId);
            Map<Long, List<String>> attrValues = skuSaleAttrValueService.getSkuAttrValues(skuIds, attr.getAttrId());
            skuItemSaleAttrVo.setAttrValues(attrValues.get(attr.getAttrId()));
            return skuItemSaleAttrVo;
        }).collect(Collectors.toList());
        skuItemVo2.setSaleAttr(collect);
        //spu描述       SpuInfoDescEntity spuInfoDesc;
        SpuInfoDescEntity spuInfoDesc = spuInfoDescService.getById(spuId);
        skuItemVo2.setSpuInfoDesc(spuInfoDesc);
        //spu规格参数    List<SkuItemAttrGroupVo> groupAttrs;
        List<Long> attrIds = productAttrValueService.getAttrIds(spuId);
        Map<Long, List<Long>> attrGroupIds = attrAttrgroupRelationService.getAttrGroupIds(attrIds);
        Set<Map.Entry<Long, List<Long>>> entries = attrGroupIds.entrySet();
        Iterator<Map.Entry<Long, List<Long>>> iterator = entries.iterator();
        List<SkuItemVo2.SpuItemAttrGroupVo> groupAttrs = new ArrayList<>();
        while (iterator.hasNext()) {
            Map.Entry<Long, List<Long>> next = iterator.next();
            Long groupId = next.getKey();
            SkuItemVo2.SpuItemAttrGroupVo spuItemAttrGroupVo = new SkuItemVo2.SpuItemAttrGroupVo();
            AttrGroupEntity attrGroup = attrGroupService.getById(groupId);
            spuItemAttrGroupVo.setGroupName(attrGroup.getAttrGroupName());
            List<Long> attrId = next.getValue();
            List<SkuItemVo2.SpuBaseAttrVo> attrs = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId).and((obj) -> {
                obj.in("attr_id", attrId);
            })).stream().map(item -> {
                SkuItemVo2.SpuBaseAttrVo spuBaseAttrVo = new SkuItemVo2.SpuBaseAttrVo();
                spuBaseAttrVo.setAttrName(item.getAttrName());
                spuBaseAttrVo.setAttrValues(item.getAttrValue());
                return spuBaseAttrVo;
            }).collect(Collectors.toList());
            spuItemAttrGroupVo.setAttrs(attrs);
            groupAttrs.add(spuItemAttrGroupVo);
        }
        skuItemVo2.setGroupAttrs(groupAttrs);
        System.out.println(JSON.toJSON(skuItemVo2));
        return skuItemVo2;
    }

    @Override
    public SkuItemVo2 getSkuDeatilBySkuId(Long skuId) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        SkuItemVo2 skuItemVo2 = new SkuItemVo2();
        CompletableFuture<Long> future = CompletableFuture.supplyAsync(() -> {
            //sku基本信息    SkuInfoEntity skuInfo;
            SkuInfoEntity skuInfo = getById(skuId);
            skuItemVo2.setSkuInfo(skuInfo);
            //sku图片信息    List<SkuImagesEntity> images;
            List<SkuImagesEntity> images = skuImagesService.getSkuImagesBySkuId(skuId);
            skuItemVo2.setImages(images);
            return skuInfo.getSpuId();
        }, executorService);
        future.thenAcceptAsync((spuId) -> {
            //sku销售属性   List<SkuItemSaleAttrVo> saleAttr
            List<SkuSaleAttrValueEntity> saleAttrs = skuSaleAttrValueService.list(new QueryWrapper<SkuSaleAttrValueEntity>().eq("sku_id", skuId));
            List<SkuItemVo2.SkuItemSaleAttrVo> collect = saleAttrs.stream().map(attr -> {
                SkuItemVo2.SkuItemSaleAttrVo skuItemSaleAttrVo = new SkuItemVo2.SkuItemSaleAttrVo();
                skuItemSaleAttrVo.setAttrId(attr.getAttrId());
                skuItemSaleAttrVo.setAttrName(attr.getAttrName());
                List<Long> skuIds = baseMapper.getSkuIdsBySpuId(spuId);
                Map<Long, List<String>> attrValues = skuSaleAttrValueService.getSkuAttrValues(skuIds, attr.getAttrId());
                skuItemSaleAttrVo.setAttrValues(attrValues.get(attr.getAttrId()));
                return skuItemSaleAttrVo;
            }).collect(Collectors.toList());
            skuItemVo2.setSaleAttr(collect);
        }, executorService);
        //spu描述       SpuInfoDescEntity spuInfoDesc;
        future.thenAcceptAsync((spuId) -> {
            SpuInfoDescEntity spuInfoDesc = spuInfoDescService.getById(spuId);
            skuItemVo2.setSpuInfoDesc(spuInfoDesc);
        }, executorService);
        //spu规格参数    List<SkuItemAttrGroupVo> groupAttrs;
        future.thenAcceptAsync((spuId) -> {
            List<Long> attrIds = productAttrValueService.getAttrIds(spuId);
            Map<Long, List<Long>> attrGroupIds = attrAttrgroupRelationService.getAttrGroupIds(attrIds);
            Set<Map.Entry<Long, List<Long>>> entries = attrGroupIds.entrySet();
            Iterator<Map.Entry<Long, List<Long>>> iterator = entries.iterator();
            List<SkuItemVo2.SpuItemAttrGroupVo> groupAttrs = new ArrayList<>();
            while (iterator.hasNext()) {
                Map.Entry<Long, List<Long>> next = iterator.next();
                Long groupId = next.getKey();
                SkuItemVo2.SpuItemAttrGroupVo spuItemAttrGroupVo = new SkuItemVo2.SpuItemAttrGroupVo();
                AttrGroupEntity attrGroup = attrGroupService.getById(groupId);
                spuItemAttrGroupVo.setGroupName(attrGroup.getAttrGroupName());
                List<Long> attrId = next.getValue();
                List<SkuItemVo2.SpuBaseAttrVo> attrs = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().in("attr_id", attrId)).stream().map(item -> {
                    SkuItemVo2.SpuBaseAttrVo spuBaseAttrVo = new SkuItemVo2.SpuBaseAttrVo();
                    spuBaseAttrVo.setAttrName(item.getAttrName());
                    spuBaseAttrVo.setAttrValues(item.getAttrValue());
                    return spuBaseAttrVo;
                }).collect(Collectors.toList());
                spuItemAttrGroupVo.setAttrs(attrs);
                groupAttrs.add(spuItemAttrGroupVo);
            }

//            attrGroupService.list(new QueryWrapper<AttrGroupEntity>().in("attr_group_id", attrGroupIds)).stream().map(item->{
//                SkuItemVo.SpuItemAttrGroupVo spuItemAttrGroupVo = new SkuItemVo.SpuItemAttrGroupVo();
//                spuItemAttrGroupVo.setGroupName(item.getAttrGroupName());
//
//            });
//            List<SkuItemVo.SpuItemAttrGroupVo> groupAttrs = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId)).stream().map(item -> {
//                SkuItemVo.SpuItemAttrGroupVo spuItemAttrGroupVo = new SkuItemVo.SpuItemAttrGroupVo();
//                List<SkuItemVo.SpuBaseAttrVo> attrs = new ArrayList<>();
//
//                spuItemAttrGroupVo.setAttrs(attrs);
//                return spuItemAttrGroupVo;
//            }).collect(Collectors.toList());
            skuItemVo2.setGroupAttrs(groupAttrs);
        }, executorService);
        System.out.println(skuItemVo2);
        return skuItemVo2;
    }

    @Override
    public BigDecimal getPrice(Long skuId) {
        return getById(skuId).getPrice();
    }
}